package com.eatwhat.controller;

import com.eatwhat.dto.ApiResponse;
import com.eatwhat.entity.Category;
import com.eatwhat.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/categories")
@CrossOrigin
public class CategoryController {
    
    @Autowired
    private CategoryService categoryService;
    
    @GetMapping
    public ApiResponse<List<Category>> getAllCategories() {
        List<Category> categories = categoryService.getAllCategories();
        return ApiResponse.success(categories);
    }
    
    @GetMapping("/enabled")
    public ApiResponse<List<Category>> getEnabledCategories() {
        List<Category> categories = categoryService.getEnabledCategories();
        return ApiResponse.success(categories);
    }
    
    @GetMapping("/{id}")
    public ApiResponse<Category> getCategoryById(@PathVariable Long id) {
        Category category = categoryService.getCategoryById(id);
        if (category == null) {
            return ApiResponse.error("分类不存在");
        }
        return ApiResponse.success(category);
    }
    
    @PostMapping
    public ApiResponse<Category> createCategory(@RequestBody Category category) {
        try {
            Category savedCategory = categoryService.saveCategory(category);
            return ApiResponse.success("创建成功", savedCategory);
        } catch (Exception e) {
            return ApiResponse.error("创建失败：" + e.getMessage());
        }
    }
    
    @PutMapping("/{id}")
    public ApiResponse<Category> updateCategory(@PathVariable Long id, @RequestBody Category category) {
        try {
            category.setId(id);
            Category savedCategory = categoryService.saveCategory(category);
            return ApiResponse.success("更新成功", savedCategory);
        } catch (Exception e) {
            return ApiResponse.error("更新失败：" + e.getMessage());
        }
    }
    
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteCategory(@PathVariable Long id) {
        try {
            categoryService.deleteCategory(id);
            return ApiResponse.success("删除成功", null);
        } catch (Exception e) {
            return ApiResponse.error("删除失败：" + e.getMessage());
        }
    }
}